package com.ocm.tourism.web.validator;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.ocm.tourism.core.domain.Participant;
import com.ocm.tourism.core.domain.RoleType;
import com.ocm.tourism.core.exception.ServicePermissionRuntimeException;
import com.ocm.tourism.core.service.ParticipantService;
import com.ocm.tourism.core.util.UserUtil;

@Component
public class ParticipantValidator implements Validator {

   @Autowired
   ParticipantService participantService;

   @Override
   public boolean supports(Class<?> clazz) {
      return clazz.getName().equalsIgnoreCase(Participant.class.getName());
   }

   @Override
   public void validate(Object target, Errors errors) {
      
   }

   public void validateParticipant(Participant participant, Errors errors) {
      Long id = participant.getId();
      String username = participant.getUsername();
      if (!errors.hasFieldErrors("username") && StringUtils.containsWhitespace(username)){
         errors.rejectValue("username", "error_has_space");
      }
      if (id != null && id > 0){
         this.validatePermission(id);
         if (!errors.hasFieldErrors("username")){
            boolean hasParticipant = this.participantService.hasParticipant(username);
            if (hasParticipant == false){
               errors.rejectValue("username", "error_participant_existed");
            }
         }
      }
   }

   public boolean validatePermission(long participantId) {
      if (UserUtil.hasRole(RoleType.ROLE_ADMIN))
         return true;

      if (UserUtil.hasRole(RoleType.ROLE_USER) && UserUtil.currentParticipantId() == participantId)
         return true;

      throw new ServicePermissionRuntimeException("The RoleType is not supported to retreive the TourismService service");
   }
}
